<template>
  <div class="manage_info_body">
    <!-- 基本信息 -->
    <el-card>
      <div slot="header">
        <el-row type="flex" justify="space-between" align="middle">
          <h4>基本信息</h4>
          <el-button
            icon="el-icon-plus"
            type="text"
            size="large"
            :disabled="$attrs.isFinished"
            @click="handleAddCustomAttr"
          >添加自定义属性</el-button
          >
        </el-row>
      </div>
      <div>
        <template v-if="basicInfo.list.length !== 0">
          <el-row>
            <el-form
              ref="formData"
              label-width="150px"
              :disabled="$attrs.isFinished"
            >
            <el-col
              :span="12"
              v-for="(item, index) in basicInfo.list"
              :key="item.attributeUuid + index"
            >
              <el-form-item
                :rules="[{ required: item.attributeMustHave === '1', message: `${item.attributeName}不能为空`, trigger: 'blur'}]"
                :label="item.attributeName"
              >
                <!-- input框 -->
                <template v-if="item.attributeType === '01'">
                  <el-input
                    class="small_input_wrap"
                    v-model.trim="item.valueInfo"
                    placeholder="请输入内容"
                    maxlength="30"
                    show-word-limit
                  ></el-input>
                </template>
                <!-- select多选框 -->
                <template v-else-if="item.attributeType === '04'">
                  <el-select
                    v-model="item.valueInfo"
                    placeholder="请选择"
                    multiple
                  >
                    <el-option
                      v-for="option in item.values"
                      :key="option.valueUuid"
                      :label="option.valueName"
                      :value="option.valueUuid"
                    >
                    </el-option>
                  </el-select>
                </template>
                <!-- select单选/文本框 -->
                <template v-else-if="item.attributeType === '05'">
                  <el-select
                    v-model="item.valueInfo"
                    filterable
                    allow-create
                    default-first-option
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="option in item.values"
                      :key="option.valueUuid"
                      :label="option.valueName"
                      :value="option.valueName"
                    />
                  </el-select>
                </template>
                <!-- select下拉 -->
                <template v-else>
                  <el-select v-model="item.valueInfo" placeholder="请选择">
                    <el-option
                      v-for="option in item.values"
                      :key="option.valueUuid"
                      :label="option.valueName"
                      :value="option.valueUuid"
                    >
                    </el-option>
                  </el-select>
                </template>
                <!-- 移除按钮 -->
                <el-button
                  v-if="item.officialFlag === 'N'"
                  type="text"
                  icon="el-icon-delete-solid"
                  :disabled="$attrs.isFinished"
                  @click="handleRemoveCustomAttr(index)"
                />
              </el-form-item>
            </el-col>
            </el-form>
          </el-row>
        </template>
      </div>
    </el-card>
    <!-- 管理属性基本信息 -->
    <card-item
      ref="manage"
      title="管理属性基本信息"
      :infoDataList="manageInfoData"
      :formData="manageInfo.formData"
      :formRules="manageInfo.formRules"
      @handleSelectRadio="handleSelectSeasonProduct"
      @getCardItemFormData="handleGetManageInfo"
      v-bind="$attrs"
    ></card-item>
    <!-- 管理属性营销信息 -->
    <card-item
      ref="marketing"
      title="管理属性营销信息"
      :infoDataList="marketingInfoData"
      :formData="marketingInfo.formData"
      :formRules="marketingInfo.formRules"
      @handleSelectMultiple="handleSelectSalePlat"
      @getCardItemFormData="handleGetMarketInfo"
      @handleVisibleChangeByMultiple="handleVisibleChangeBySalePlat"
      v-bind="$attrs"
    ></card-item>
    <!-- 管理属性税务信息 -->
    <card-item
      ref="tax"
      title="管理属性税务信息"
      :infoDataList="taxInfoData"
      :formData="taxInfo.formData"
      :formRules="taxInfo.formRules"
      @handleSelectRadio="handleSelectTaxInfo"
      @getCardItemFormData="handleGetTaxInfo"
      v-bind="$attrs"
    ></card-item>
    <!-- 管理属性物流信息 -->
    <card-item
      ref="logistics"
      title="管理属性物流信息"
      placeholder="物流人员维护"
      notShowItem="logistics_stock"
      :infoDataList="logisticsInfoData"
      :formData="logisticsInfo.formData"
      :formRules="logisticsInfo.formRules"
      @getCardItemFormData="handleGetLogisticsInfo"
      v-bind="$attrs"
    ></card-item>
    <!-- 基本信息 - 添加自定义属性 -->
    <basic-dialog
      title="添加自定义属性"
      width="50%"
      :visible="basicInfo.visible"
      :handleOk="hanldeCustomAttrOk"
      :handleClose="hanldeCustomAttrCancel"
    >
      <el-input
        v-model="basicInfo.label"
        placeholder="请输入自定义属性名称"
        maxlength="6"
        show-word-limit
      />
    </basic-dialog>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import CardItem from '../components/card/cardItem';
import BasicDialog from '@/components/BasicDialog';
import { isResponseSuccess } from '@/utils/bizUtils';
import { getLoadingFn } from '@/utils/loading';
export default {
  components: {
    CardItem,
    BasicDialog
  },
  props: {
    basicInfoList: {
      type: Array,
      default () {
        return [];
      }
    },
    manageInfoList: {
      type: Array,
      default () {
        return [];
      }
    },
    marketingInfoList: {
      type: Array,
      default () {
        return [];
      }
    },
    taxInfoList: {
      type: Array,
      default () {
        return [];
      }
    },
    logisticsInfoList: {
      type: Array,
      default () {
        return [];
      }
    },
    productType: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      basicInfo: {
        visible: false,
        label: '',
        list: []
      },
      manageInfo: {
        formData: {},
        formRules: {}
      },
      marketingInfo: {
        formData: {},
        formRules: {}
      },
      taxInfo: {
        formData: {},
        formRules: {}
      },
      logisticsInfo: {
        formData: {},
        formRules: {}
      },
      manageAttributeData: {}
    };
  },
  watch: {
    basicInfoList (list) {
      this.basicInfo.list = list.reduce((value, item) => {
        if (item.attributeType === '04') {
          item.valueInfo = item.valueInfo ? item.valueInfo.split(',') : [];
        }
        value.push(item);
        return value;
      }, []);
    }
  },
  computed: {
    manageInfoData () {
      return this.dealInfoDataFn({
        targetName: 'manageInfo',
        list: this.manageInfoList
      });
    },
    marketingInfoData () {
      // 商品类型为租赁商品、样品、自用商品、周转工装时，默认勾选鸿鹄系统
      const defaultSwanCheckedList = ['04', '05', '08', '09'];
      const list = this.marketingInfoList;
      if (defaultSwanCheckedList.includes(this.productType)) {
        list[0].valueInfo = 'marketing_saleplat_swan';
      }
      // 商品类型为项目商品时，默认不勾选签约平台和分销平台
      if (this.productType === '10') {
        const valueInfoList = list[0].valueInfo.split(',');
        list[0].valueInfo = valueInfoList.filter(
          item => !['marketing_saleplat_signed', 'marketing_saleplat_distribution'].includes(item)
        ).join(',');
      }
      // 经销商品默认勾选分销平台
      if (this.productType === '01') {
        if (!list[0].valueInfo) {
          list[0].valueInfo = 'marketing_saleplat_distribution';
        } else {
          const valueInfoList = list[0].valueInfo.split(',');
          if (!valueInfoList.includes('marketing_saleplat_distribution')) {
            list[0].valueInfo = list[0].valueInfo.concat(',marketing_saleplat_distribution');
          }
        }
      }
      return this.dealInfoDataFn({
        targetName: 'marketingInfo',
        list
      });
    },
    taxInfoData () {
      return this.dealInfoDataFn({
        targetName: 'taxInfo',
        list: this.taxInfoList
      });
    },
    logisticsInfoData () {
      return this.dealInfoDataFn({
        targetName: 'logisticsInfo',
        list: this.logisticsInfoList
      });
    },
  },
  methods: {
    /* 获取整个管理属性tabs页面的接口入参数据 */
    getManageAttributesFn () {
      this.manageAttributeData.notSpecList = this.basicInfo.list.reduce((value, item) => {
        let valueInfo = item.valueInfo;
        if (_.isArray(item.valueInfo)) {
          valueInfo = item.valueInfo.join(',');
        }
        value.push({
          attrInfo: item.attrInfo || item.attributeUuid,
          officialFlag: item.officialFlag,
          valueInfo
        });
        return value;
      }, []);
      /* 依次校验每个card的表单 */
      const items = ['manage', 'marketing', 'tax', 'logistics'];
      for (let i = 0; i < items.length; i++) {
        this.$refs[items[i]].transferCardItemFormDataFn();
      }
      this.$emit('getManageAttributeData', this.manageAttributeData);
    },
    /* 重新组装各card对应的模块数据，重组入参供保存接口调用 */
    reassembleInfoDataFn (list) {
      return list.reduce((value, item) => {
        value.push({
          attrUuid: item.attributeUuid,
          valueInfo: item.valueInfo
        });
        return value;
      }, []);
    },
    /* 获取设置后的管理属性基本信息 */
    handleGetManageInfo (data) {
      this.manageAttributeData.basicManageList = this.reassembleInfoDataFn(data);
    },
    /* 获取设置后的管理属性营销信息 */
    handleGetMarketInfo (data) {
      this.manageAttributeData.marketingList = this.reassembleInfoDataFn(data);
    },
    /* 获取设置后的管理属性税务信息 */
    handleGetTaxInfo (data) {
      this.manageAttributeData.taxList = this.reassembleInfoDataFn(data);
    },
    /* 获取设置后的管理属性物流信息 */
    handleGetLogisticsInfo (data) {
      this.manageAttributeData.logisticsList = this.reassembleInfoDataFn(data);
    },
    /* 处理各对应card所需formData数据以及formRules，formList */
    dealInfoDataFn (data) {
      const { targetName, list } = data;
      let dataList = _.cloneDeep(list);
      dataList.forEach((item) => {
        item.formItemType = _.camelCase(item.attributeUuid); // 将attributeUuid字符串转换为驼峰写法作为key
      });
      this.$data[targetName].formData = dataList.reduce((value, item) => {
        value[item.formItemType] = item.valueInfo;
        if (item.attributeType === '04') {
          value[item.formItemType] = item.valueInfo ? item.valueInfo.split(',') : [];
        }
        return value;
      }, {});
      this.$data[targetName].formRules = dataList.reduce((value, item) => {
        if (item.attributeMustHave === '1') {
          value[item.formItemType] = [
            { required: true, message: `${item.attributeName}不能为空` }
          ];
        }
        return value;
      }, {});
      return dataList;
    },
    /* 点击添加自定义属性按钮事件 */
    handleAddCustomAttr () {
      this.basicInfo.visible = true;
    },
    /* 点击取消按钮事件-取消自定义属性的添加操作 */
    hanldeCustomAttrCancel () {
      this.basicInfo.visible = false;
    },
    /* 添加自定义属性确定事件 */
    hanldeCustomAttrOk () {
      let index = _.findIndex(this.basicInfo.list, (item) => {
        return item.attrUuid === this.basicInfo.label;
      });
      if (index !== -1) {
        return this.$message.warning('该属性名称已被占用');
      }
      this.basicInfo.list.push({
        officialFlag: 'N',
        attributeType: '01',
        attributeMustHave: '1',
        attributeUuid: this.basicInfo.label,
        attributeName: this.basicInfo.label,
        attrInfo: this.basicInfo.label,
        attrUuid: this.basicInfo.label,
        valueInfo: ''
      });
      this.basicInfo.label = '';
      this.basicInfo.visible = false;
    },
    /* 移除自定义属性 */
    handleRemoveCustomAttr (index) {
      this.basicInfo.list.splice(index, 1);
    },
    /* 处理多选下拉逻辑 */
    handleSelectSalePlat (data) {
      const { val, item, formData } = data;
      const notSaleIndex = val.indexOf('marketing_saleplat_notsale');
      if (notSaleIndex !== -1) {
        if (val.length === notSaleIndex + 1) {
          formData[item.formItemType] = ['marketing_saleplat_notsale'];
        } else {
          formData[item.formItemType].splice(notSaleIndex, 1);
        }
      } else {
        formData[item.formItemType] = val;
      }
    },
    // 多选框下拉显隐 售卖平台选择
    handleVisibleChangeBySalePlat (data) {
      const { visible, item, formData } = data;
      if (visible) { return false; }
      const isProjectGoods = this.productType === '10';
      const isSaleplat = item.attributeUuid === 'marketing_saleplat';
      if (isSaleplat && isProjectGoods) {
        this.confirmBySelectDefaultNotChecked({
          val: formData[item.formItemType],
          item,
          formData
        });
      }
    },
    // 售卖平台默认不勾选确认弹框
    confirmBySelectDefaultNotChecked ({ val, item, formData }) {
      const defaultNotCheckedVals = ['marketing_saleplat_signed', 'marketing_saleplat_distribution']; // 签约平台，分销平台
      const hasDefaultVal = val.some(item => defaultNotCheckedVals.includes(item));
      if (hasDefaultVal) {
        const multipleRef = this.$refs.marketing.$refs.el_multiple_select;
        const index = multipleRef.findIndex(vueComp => vueComp.name === item.formItemType);
        if (index !== -1) {
          multipleRef[index].visible = false;
        }
        this.$confirm(
          '确认要在 签约平台/分销平台 销售此项目商品吗？',
          { title: '提示', type: 'warning' }
        ).then(() => {
          formData[item.formItemType] = val;
        }).catch(() => {
          formData[item.formItemType] = val.filter(v => !defaultNotCheckedVals.includes(v));
        });
      } else {
        formData[item.formItemType] = val;
      }
    },
    /* 选择是否季节性商品事件 */
    handleSelectSeasonProduct (data) {
      const { val, formData, item } = data;
      if (item.attributeUuid !== 'manage_season_product') {
        return false;
      }
      const stockIndex = this.manageInfoData.findIndex(item => { return item.attributeUuid === 'manage_stock_period' });
      const soldoutIndex = this.manageInfoData.findIndex(item => { return item.attributeUuid === 'manage_soldout_period' });
      /* 季节性为否的时候，清空囤货期和下架期的数据，并且禁用输入框 */
      if (val === 'manage_season_product_no') {
        formData.manageStockPeriod = ''; // 囤货期
        formData.manageSoldoutPeriod = ''; // 下架期
        this.manageInfoData[stockIndex].canEdit = 'N';
        this.manageInfoData[soldoutIndex].canEdit = 'N';
      }
      if (val === 'manage_season_product_yes') {
        this.manageInfoData[stockIndex].canEdit = 'Y';
        this.manageInfoData[soldoutIndex].canEdit = 'Y';
      }
    },
    /* 是季节性商品时，对囤货期和下架期的必填校验方法 */
    isSeasonMandatoryCheckFunc (source) {
      const seasonMandatory = {
        name: 'manage_season_product',
        value: 'manage_season_product_yes'
      }
      const seasonProduct = source.find(item => item.attrUuid === seasonMandatory.name);
      if (!seasonProduct) {
        return false;
      }
      /* 如果不是季节性，就不必校验必填 */
      if (seasonProduct.valueInfo !== seasonMandatory.value) {
        return true;
      }
      const linkedSeasonItem = ['manage_stock_period', 'manage_soldout_period'];
      const stockAndSoldoutList = source.filter(item => {
        return linkedSeasonItem.includes(item.attrUuid);
      });
      const flag = stockAndSoldoutList.every(item => item.valueInfo);
      if (!flag) {
        this.$message.warning('季节性商品的囤货期和下架期必填');
      }
      return flag;
    },
    /* 选择税类事件 */
    handleSelectTaxInfo (data) {
      const { val, formData } = data;
      const params = { uuid: val };
      this.getTaxInfoDataAction(params).then((res) => {
        if (!res) {
          return false;
        }
        const { taxCateNo, taxRate } = res;
        formData.taxCode = taxCateNo;
        formData.taxRate = taxRate;
      });
    },
    /* 据归类UUID，查询税类代码taxCateNo、销售税率taxRate */
    getTaxInfoDataAction (params) {
      let loadingInstance = getLoadingFn('manage_info_body');
      return new Promise((resolve, reject) => {
        ApiRequest(
          `/sysback/addsingleproduct/basicinfo/getClassificationByUuid?uuid=${params.uuid}`,
          'post',
          params
        ).then((res) => {
          loadingInstance.close();
          if (!isResponseSuccess(res)) {
            resolve(false);
            return false;
          }
          const data = {
            taxCateNo: res.retData.taxCateNo,
            taxRate: res.retData.taxRate
          };
          resolve(data);
        }).catch(() => {
          loadingInstance.close();
        });
      });
    },
    /* 重置售卖平台的方法
       保存校验时，当商品四级类的是否限制类为危化品，并且是一级的时候（后端校验），将售卖平台的普通平台的勾选取消)
    */
    resetSalePlatFunc () {
      const normalIndex = this.marketingInfo.formData.marketingSaleplat.indexOf('marketing_saleplat_normal');
      if (normalIndex === -1) { return false }
      this.marketingInfo.formData.marketingSaleplat.splice(normalIndex, 1);
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .el-card__header {
  padding: 5px 15px;
}
.red_color {
  color: #f56c6c;
}
.row_item_wrap {
  margin: 10px 10px 10px 0px;
  /deep/ .small_input_wrap {
    width: 50.5%;
  }
  .custom_attr_title {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
  }
}
.card_item_wrap {
  margin-top: 10px;
}

.title_wrap {
  height: 40px;
  line-height: 40px;
}

.input_button_color {
  color: #ffffff !important;
  background-color: #5a9cf8 !important;
}

.el-form-item {
  /deep/ .small_input_wrap {
    width: 50.5%;
  }
  /deep/ .el-select--small {
    width: 50.5%;
  }
}
</style>
